package com.topisv.tms.utils.sf;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.WarehouseAddress;
import com.topisv.tms.webservice.soap.sf.vo.CreateSFVO;

public class MailSFUtil {
	
	private static final Logger log = LoggerFactory.getLogger(MailSFUtil.class);
	
	private static String Init = "7690665895";
	private static String sf_url = "http://bsp-oisp.sf-express.com/bsp-oisp/sfexpressService";//"http://bspoisp.sit.sf-express.com:11080/bsp-oisp/sfexpressService";//"http://bsp-oisp.sf-express.com/bsp-oisp/sfexpressService";
	private static String checkword = "RP4jfKIvUZOp6GbcM7GHTFmSDRzohjhV";//"FhUQNdsq1u8TM0dQ";//"PpALECcs8w1jC9fzdUoHJWaHbEDypMI3";
	/*private static Map<String, String> mouthMaps=new HashMap<String, String>();
	static{
		try {
			Properties p=InitProperties.initWeService();
		    String params=p.getProperty("sfParams");
		    if(params!=null){
		    	Init=params;
		    }
		    String sfMonth=p.getProperty("sfMonth");
		    if(sfMonth!=null){
		    	String[] lists=sfMonth.split(",");
		    	for(String list:lists){
		    		String[] ls=list.split(":");
		    		mouthMaps.put(ls[0], ls[1]);
		    	}
		    }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			
		}
		
	}
	
	public static String getKey(String key){
		return mouthMaps.get(key);
	}*/

	//创建订单
	public static String createOrdeno(EdiOrder e,List<EdiGoodsSku> skuList,String express_type,WarehouseAddress warehouseAddress){
		try{
			log.info("顺丰创建订单");
		Document  document=DocumentHelper.createDocument();
		Element rootElement=document.addElement("Request");
		rootElement.addAttribute("service", "OrderService");
		rootElement.addAttribute("lang", "zh-CN");
		//head
		Element headElement=rootElement.addElement("Head");
		headElement.setText("5715044232");//shplcc  HZNRW
		
		//body
		Element bodyElement=rootElement.addElement("Body");
		Element orderElement=bodyElement.addElement("Order");
		//order
		orderElement.addAttribute("orderid", e.getOrdeno());//订单号
		orderElement.addAttribute("express_type", express_type);
		orderElement.addAttribute("pay_method", "1");//付款方式
		orderElement.addAttribute("j_company", warehouseAddress.getCompany());
		orderElement.addAttribute("j_contact", warehouseAddress.getContact());
		orderElement.addAttribute("j_tel", warehouseAddress.getMobile());
		orderElement.addAttribute("j_province", warehouseAddress.getProvName());
		orderElement.addAttribute("j_address", warehouseAddress.getAddress());
		orderElement.addAttribute("j_city", warehouseAddress.getCityName());

		String volume= "";
		String weight="";
		String skuName="";
		String unit = "个";
//		if("MID".equals(e.getCustomerCode()))
//		{
//			if("single".equals(e.getOrderType()))
//			{
//			
//				try {
//					float length = Float.parseFloat(skuList.get(0).getLen())/10;
//					float width = Float.parseFloat(skuList.get(0).getWid())/10;
//					float height = Float.parseFloat(skuList.get(0).getHei())/10;
//					volume = length*width*height + "";
//				} catch (NumberFormatException e1) {
//					volume="0";
//				}
//				skuName = skuList.get(0).getSkuName();
//				weight = (skuList.get(0).getWeight() + skuList.get(0).getWeightPkg())/1000 + "";
//				unit = skuList.get(0).getUnit();
//			}
//			else
//			{
//				int _weight=0;
//				for(EdiGoodsSku sku : skuList)
//				{
//					if("1".equals(sku.getSellFlg()))
//					{
//						try {
//							float length = Float.parseFloat(sku.getLen())/10;
//							float width = Float.parseFloat(sku.getWid())/10;
//							float height = Float.parseFloat(sku.getHei())/10;
//							volume = length*width*height + "";
//						} catch (NumberFormatException e1) {
//							volume="0";
//						}
//						skuName = sku.getSkuName();
//						unit=sku.getUnit();
//					}
//					_weight += sku.getWeight()+sku.getWeightPkg();
//				}
//				weight = _weight/1000 + "";
//			}
//		}
//		else
//		{
//			volume = "0";
//			if("single".equals(e.getOrderType()))
//			{
//				weight = (skuList.get(0).getWeight() + skuList.get(0).getWeightPkg())/1000 + "";
//				unit = skuList.get(0).getUnit();
//				skuName = skuList.get(0).getSkuName();
//			}
//			else
//			{
//				int _weight=0;
//				for(EdiGoodsSku sku : skuList)
//				{
//					_weight += sku.getWeight()+sku.getWeightPkg();
//					skuName = sku.getSkuName();
//				}
//				weight = _weight/1000 + "";
//			}
//		}
		
		if("single".equals(e.getOrderType())){
//				weight = (skuList.get(0).getWeight() + skuList.get(0).getWeightPkg())/1000 + "";
				unit = skuList.get(0).getUnit();
				skuName = skuList.get(0).getSkuName();
		}
		else
		{
			int _weight=0;
			for(EdiGoodsSku sku : skuList)
			{
//				_weight += sku.getWeight()+sku.getWeightPkg();
				skuName = sku.getSkuName();
			}
//			weight = _weight/1000 + "";
		}
//		orderElement.addAttribute("volume", volume);
//		orderElement.addAttribute("cargo_total_weight", weight);
		//orderElement.addAttribute("custid", "7690665895");//虎门月结账号
		orderElement.addAttribute("custid", warehouseAddress.getSfmonth());
		
		orderElement.addAttribute("d_contact", e.getRecena());
		orderElement.addAttribute("d_tel", (e.getMobile()==null || "".equals(e.getMobile()))?e.getTeleph():e.getMobile());
		orderElement.addAttribute("d_address", e.getAddres());
		orderElement.addAttribute("parcel_quantity", "1");//包裹数
		orderElement.addAttribute("d_province", e.getProvna());
		orderElement.addAttribute("d_city", e.getCityna());
		orderElement.addAttribute("is_gen_bill_no", "1");//是否申请运单号
//		orderElement.addAttribute("template", warehouseAddress.getContact());
		
		Element cargoElement=orderElement.addElement("Cargo");
		cargoElement.addAttribute("name", skuName);
		cargoElement.addAttribute("count", "1");
		cargoElement.addAttribute("unit", unit);
		cargoElement.addAttribute("weight", "");
		cargoElement.setText("");
		log.info("顺丰创单xml:"+document.asXML());
		return document.asXML();
		}catch(Exception e1){
			e1.printStackTrace();
		}
		return null;
	}
	
	//取消订单
	public static String confirmCancelOrdeno(EdiOrder e){
		Document  document=DocumentHelper.createDocument();
		Element rootElement=document.addElement("Request");
		rootElement.addAttribute("service", "OrderConfirmService");
		rootElement.addAttribute("lang", "zh-CN");
		
		//head
		Element headElement=rootElement.addElement("Head");
		headElement.setText("SHPL");
		
		//body
		Element bodyElement=rootElement.addElement("Body");
		Element orderElement=bodyElement.addElement("OrderConfirm");
		orderElement.addAttribute("orderid", "PD1433314190792");
		orderElement.addAttribute("mailno", "444008548984");
		orderElement.addAttribute("dealtype", "2");//1确认 2取消
		return document.asXML();
	}
	
	//查询订单
	public static String searchOrdeno(String ordeno){
		Document  document=DocumentHelper.createDocument();
		Element rootElement=document.addElement("Request");
		rootElement.addAttribute("service", "OrderSearchService");
		rootElement.addAttribute("lang", "zh-CN");
		
		//head
		Element headElement=rootElement.addElement("Head");
		headElement.setText("SHPL");
		
		//body
		Element bodyElement=rootElement.addElement("Body");
		Element orderElement=bodyElement.addElement("OrderSearch");
		orderElement.addAttribute("orderid", "PD1433314190792");
		return document.asXML();
	}
	
	//筛单,暂时不使用
	public static String filterOrdeno(EdiOrder e){
		Document  document=DocumentHelper.createDocument();
		Element rootElement=document.addElement("Request");
		rootElement.addAttribute("service", "OrderFilterService");
		rootElement.addAttribute("lang", "zh-CN");
		
		//head
		Element headElement=rootElement.addElement("Head");
		headElement.setText(Init);
		
		//body
		Element bodyElement=rootElement.addElement("Body");
		Element orderElement=bodyElement.addElement("OrderConfirm");
		orderElement.addAttribute("orderid", e.getOrdeno());
		orderElement.addAttribute("filter_type", "1");//1自动筛单 2人工筛单
		orderElement.addAttribute("d_address", e.getAddres());
		return document.asXML();
	}
	
	//路由查询
	public static String routeOrdeno(String ordeno){
		Document  document=DocumentHelper.createDocument();
		Element rootElement=document.addElement("Request");
		rootElement.addAttribute("service", "RouteService");
		rootElement.addAttribute("lang", "zh-CN");
		
		//head
		Element headElement=rootElement.addElement("Head");
		headElement.setText("SHPL");
		
		//body
		Element bodyElement=rootElement.addElement("Body");
		Element orderElement=bodyElement.addElement("RouteRequest");
		orderElement.addAttribute("tracking_number", "444008549006");//tracking_type为1该值为运单号，为2该值为订单号。(多个以逗号分隔)
		orderElement.addAttribute("tracking_type", "1");//1:根据运单号查询， 2：根据订单号查询
		orderElement.addAttribute("method_type", "1");//1：标准查询，2：定制查询
		return document.asXML();
	}
	
	/**
	 * 推送处理成功
	 * @return
	 */
	public String routePushOK() {
		return "<Response service=\"RoutePushService\"><Head>OK</Head></Response>";
	}
	
	/**
	 * 推送处理失败
	 * @return
	 */
	public String routePushERROR() {
		return "<Response service=\"RoutePushService\"><Head>ERR</Head><ERROR code=\"\">失败原因</ERROR></Response>";
	}
	
	public static CreateSFVO getSFMailNo(EdiOrder e,List<EdiGoodsSku> skuList,String express_type,WarehouseAddress warehouseAddress){
		 String xml=createOrdeno(e,skuList,express_type,warehouseAddress);
		 
		 //xml = xml.replace("\n", "");
		 log.info("申请顺丰运单号：" + xml);
		 String verifyCode = Util.md5EncryptAndBase64(xml+checkword);
		 String result = HttpPost(sf_url,xml,verifyCode);
		 log.info("申请顺丰运单号result:"+result);
	    return parseXML(result);
	}
	
	public static String HttpPost(String url,String xml,String verifyCode){
		StringBuffer sb = new StringBuffer();;
		try {
			HttpClient client = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			parameters.add(new BasicNameValuePair("xml", xml));
			parameters.add(new BasicNameValuePair("verifyCode", verifyCode));
			
			httpPost.setEntity(new UrlEncodedFormEntity(parameters, Charset.forName("UTF-8")));
			

			HttpResponse httpResponse = client.execute(httpPost);
			
			//System.out.println(httpResponse.getStatusLine().getStatusCode());
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), Charset.forName("UTF-8")));
			String content = null;
			while ((content = reader.readLine()) != null) {
			    sb.append(content);
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return sb.toString();
		
	}
	
	public static CreateSFVO parseXML(String xml){
		CreateSFVO createSFVO=new CreateSFVO();
		try {
			Document document = DocumentHelper.parseText(xml);
			Element rootElement = document.getRootElement();
			String serviceName = rootElement.attributeValue("service");
			createSFVO.setServiceName(serviceName);
			Element headElement = rootElement.element("Head");
			String headText = headElement.getText();
			createSFVO.setHeadText(headText);
			if ("OK".equals(headText)) {
				Element bodyElement = rootElement.element("Body");
				Element responseElement = bodyElement.element("OrderResponse");
				String filter_result = responseElement.attributeValue("filter_result");
				createSFVO.setFilterResult(filter_result);
				String destcode = responseElement.attributeValue("destcode");
				createSFVO.setDestcode(destcode);
				String mailno = responseElement.attributeValue("mailno");
				createSFVO.setMailno(mailno);
				String origincode = responseElement.attributeValue("origincode");
				createSFVO.setOrigincode(origincode);
				String orderid = responseElement.attributeValue("orderid");
				createSFVO.setOrderid(orderid);
			} else if ("ERR".equals(headText)) {
				Element errorElement = rootElement.element("ERROR");
				String code = errorElement.attributeValue("code");
				createSFVO.setCode(code);
				createSFVO.setErrorText(errorElement.getText());
			}

		} catch (DocumentException e1) {
			// TODO Auto-generated catch block
			
			return null;
		}
		//log.info(result);
		return createSFVO;
	}
	
	public static void main(String[] args)
	{
		String url = "http://bsp-oisp.test.sf-express.com:6080/bsp-oisp/sfexpressService";
		String checkword = "J7RO865AjMMZMkPO";
		Document  document=DocumentHelper.createDocument();
		Element rootElement=document.addElement("Request");
		rootElement.addAttribute("service", "OrderService");
		rootElement.addAttribute("lang", "zh-CN");
		//head
		Element headElement=rootElement.addElement("Head");
		headElement.setText("SHPL");
		
		//body
		Element bodyElement=rootElement.addElement("Body");
		Element orderElement=bodyElement.addElement("Order");
		//order
		orderElement.addAttribute("orderid", "PD1433584676712");
		orderElement.addAttribute("express_type", "3");
		orderElement.addAttribute("pay_method", "1");
		orderElement.addAttribute("j_company", "上海派联仓储管理有限公司");
		orderElement.addAttribute("j_contact", "虎门仓");
		orderElement.addAttribute("j_tel", "18689458013");
		orderElement.addAttribute("j_province", "广东省");
		orderElement.addAttribute("j_address", "广东省广州市增城市第四工业区新兴路增益物流园仓库");
		String volume= "0";
		String weight="5";
		String skuName="电饭煲（锅）MB-WFS4017TM";
		String unit = "台";
		
		
		orderElement.addAttribute("volume", volume);
		orderElement.addAttribute("cargo_total_weight", weight);
		orderElement.addAttribute("custid", "7690665895");
		
		orderElement.addAttribute("d_contact", "朱楚海");
		orderElement.addAttribute("d_tel", "13128380189");
		orderElement.addAttribute("d_address", "广东省揭阳市惠来县地址：广东省揭阳市惠来县仙庵镇京陇管区 省揭阳市惠来县仙庵镇京陇管区");
		orderElement.addAttribute("parcel_quantity", "1");
		orderElement.addAttribute("d_province", "广东省");
		orderElement.addAttribute("d_city", "揭阳市");
		orderElement.addAttribute("is_gen_bill_no", "1");//是否申请运单号
		orderElement.addAttribute("template", "派联_广州仓");//是否申请运单号
		
		Element cargoElement=orderElement.addElement("Cargo");
		cargoElement.addAttribute("name", skuName);
		cargoElement.addAttribute("count", "1");
		cargoElement.addAttribute("unit", unit);
		cargoElement.addAttribute("weight", weight);
		cargoElement.setText("");
		String xml = document.asXML();
		System.out.println(xml);
		
		String verifyCode = Util.md5EncryptAndBase64(xml+checkword);
		System.out.println(verifyCode);
		String result = HttpPost(url,xml,verifyCode);
		System.out.println(result);
		
	}
   
}
